#!/usr/bin/python3
# -*- coding: utf-8 -*-

import RPi.GPIO as GPIO	  # GPIO
import netifaces          # 获取本机网卡信息
import json
import socket
import time

def led_crl(led_state):
    if len(led_state) > 0 :
        if int(led_state) == 0 :
            GPIO.output(16, GPIO.LOW)
            print("led_off...")
        elif int(led_state) == 1 :
            GPIO.output(16, GPIO.HIGH)
            print("led_on...")


#create socket (UDP)
sudp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print ("Socket Created Success!")

#设置socket选项
sudp.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR|socket.SO_BROADCAST,1)
# 获取局域网ip与设置端口
addr_dict = netifaces.ifaddresses('wlan0')
ip = addr_dict[netifaces.AF_INET][0]['addr']
port = 3861

# 绑定端口号
sudp.bind((ip, port))

try:
    while True:
        rec = sudp.recv(65535)
        if len(rec) < 0 :
            continue
        print("rec: "+str(rec))
        GPIO.setwarnings(False) #close warning
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(16, GPIO.OUT)
        led_crl(rec)

except Exception as e:
    print(e)
finally:
    sudp.close()
    GPIO.cleanup()
    print("end...")
